# -*- coding: utf-8 -*-
from flask import abort, json, request
from config import CLIENT_ID, CLIENT_SECRET, REDIRECT_URL
from functools import wraps
from model.user_token import UserToken
import urllib
import urllib2
import inspect
__ssl__ = __import__('ssl')


try:
    _ssl = __ssl__._ssl
except AttributeError:
    _ssl = __ssl__._ssl2


OldSSLSocket = __ssl__.SSLSocket


class NewSSLSocket(OldSSLSocket):
    """Fix SSLSocket constructor."""
    def __init__(
        self, sock, keyfile=None, certfile=None, server_side=False,
        cert_reqs=__ssl__.CERT_REQUIRED, ssl_version=2, ca_certs=None,
        do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None,
        server_hostname=None, _context=None
    ):
        OldSSLSocket.__init__(
            self, sock, keyfile=keyfile, certfile=certfile,
            server_side=server_side, cert_reqs=cert_reqs,
            ssl_version=ssl_version, ca_certs=ca_certs,
            do_handshake_on_connect=do_handshake_on_connect,
            suppress_ragged_eofs=suppress_ragged_eofs, ciphers=ciphers
        )


def new_sslwrap(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=__ssl__.CERT_NONE, ssl_version=__ssl__.PROTOCOL_SSLv23, ca_certs=None, ciphers=None):
    context = __ssl__.SSLContext(ssl_version)
    context.verify_mode = cert_reqs or __ssl__.CERT_NONE
    if ca_certs:
        context.load_verify_locations(ca_certs)
    if certfile:
        context.load_cert_chain(certfile, keyfile)
    if ciphers:
        context.set_ciphers(ciphers)

    caller_self = inspect.currentframe().f_back.f_locals['self']
    return context._wrap_socket(sock, server_side=server_side, ssl_sock=caller_self)


#if not hasattr(_ssl, 'sslwrap'):
#    _ssl.sslwrap = new_sslwrap
#    __ssl__.SSLSocket = NewSSLSocket


def get_weibo_access_token(code):
    """
### sample return from weibo api:

    {
          "access_token": "ACCESS_TOKEN",
          "expires_in": 1234,
          "remind_in":"798114",
          "uid":"12341234"
    }
    """
    url = 'https://api.weibo.com/oauth2/access_token'
    data = urllib.urlencode({
        'client_id'    : CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'grant_type'   : 'authorization_code',
        'code'         : code,
        'redirect_uri' : REDIRECT_URL
    })

    try:
        resp = urllib2.urlopen(url, data=data)
    except:
        return {}

    return json.loads(resp.read())

def get_weibo_info(uid, access_token):
    """
### sample return from weibo api:

    {
        "id": 1404376560,
        "screen_name": "zaku",
        "name": "zaku",
        "province": "11",
        "city": "5",
        "location": "北京 朝阳区",
        "description": "人生五十年，乃如梦如幻；有生斯有死，壮士复何憾。",
        "url": "http://blog.sina.com.cn/zaku",
        "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
        "domain": "zaku",
        "gender": "m",
        "followers_count": 1204,
        "friends_count": 447,
        "statuses_count": 2908,
        "favourites_count": 0,
        "created_at": "Fri Aug 28 00:00:00 +0800 2009",
        "following": false,
        "allow_all_act_msg": false,
        "geo_enabled": true,
        "verified": false,
        "status": {
            "created_at": "Tue May 24 18:04:53 +0800 2011",
            "id": 11142488790,
            "text": "我的相机到了。",
            "source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
            "favorited": false,
            "truncated": false,
            "in_reply_to_status_id": "",
            "in_reply_to_user_id": "",
            "in_reply_to_screen_name": "",
            "geo": null,
            "mid": "5610221544300749636",
            "annotations": [],
            "reposts_count": 5,
            "comments_count": 8
        },
        "allow_all_comment": true,
        "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",
        "verified_reason": "",
        "follow_me": false,
        "online_status": 0,
        "bi_followers_count": 215
    }
    """
    url = 'https://api.weibo.com/2/users/show.json?access_token=%s&uid=%s' \
            % (access_token, uid)
    try:
        resp = urllib2.urlopen(url)
    except:
        return {}

    return json.loads(resp.read())


def user_auth(user_id='user_id'):
    def wrapper(func):
        @wraps(func)
        def _wrapper(*args, **kwargs):
            # get user id
            _id = request.args.get(user_id, None) \
                  or request.form.get(user_id, None) \
                  or request.view_args.get(user_id, None)
            if _id is None:
                abort(401)
            token = request.args.get('token') or request.form.get('token')
            # try to get token from cookie
            if not token:
                token = request.cookies.get('token')
            if not UserToken.find({'_id': token, UserToken.Field.userId: _id}):
                abort(401)
            return func(*args, **kwargs)
        return _wrapper
    return wrapper
